package com.medical.controller;

import com.medical.model.entity.Dept;
import com.medical.model.entity.Employee;
import com.medical.service.DeptService;
import com.medical.service.IEmployeeService;
import com.medical.domain.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author TISNIW
 * @version 1.0
 * @desc
 */
@RestController
@RequestMapping("/data")
public class DataController {
    @Autowired
    private DeptService deptService;

    @Autowired
    private IEmployeeService employeeService;

    @GetMapping("/deptEmployeeCount")
    public R<Map<String, Object>> getDeptEmployeeCount() {
        // 获取所有部门
        List<Dept> allDepts = deptService.list();
        // 获取所有员工
        List<Employee> allEmployees = employeeService.list();

        // 构建部门ID到员工数量的映射
        Map<Long, Integer> deptEmpCountMap = new HashMap<>();
        for (Employee emp : allEmployees) {
            Long deptId = emp.getDeptId();
            deptEmpCountMap.put(deptId, deptEmpCountMap.getOrDefault(deptId, 0) + 1);
        }

        // 构建部门树结构并计算每个父部门下的员工总数
        Map<Long, Dept> deptMap = new HashMap<>();
        for (Dept dept : allDepts) {
            deptMap.put(dept.getId(), dept);
        }
        List<Map<String, Object>> result = new ArrayList<>();
        for (Dept dept : allDepts) {
            Map<String, Object> item = new HashMap<>();
            item.put("id", dept.getId());
            item.put("name", dept.getName());
            item.put("parentId", dept.getParentId());
            item.put("employeeCount", deptEmpCountMap.getOrDefault(dept.getId(), 0));
            result.add(item);
        }

        // 计算每个父部门下的员工总数
        for (Map<String, Object> item : result) {
            Long parentId = (Long) item.get("parentId");
            while (parentId != null && deptMap.containsKey(parentId)) {
                Map<String, Object> parentItem = findItemById(result, parentId);
                if (parentItem != null) {
                    int currentCount = (int) parentItem.get("employeeCount");
                    parentItem.put("employeeCount", currentCount + (int) item.get("employeeCount"));
                }
                parentId = (Long) deptMap.get(parentId).getParentId();
            }
        }

        return R.ok(Collections.singletonMap("depts", result));
    }

    private Map<String, Object> findItemById(List<Map<String, Object>> items, Long id) {
        for (Map<String, Object> item : items) {
            if (id.equals(item.get("id"))) {
                return item;
            }
        }
        return null;
    }
}
